#! usr/bin/python

# -*- coding: utf-8 -*-


#from parsers import parser_H2
import subprocess
from core import clustering as clust, objects as obj
from PyQt4 import QtGui
import os.path as path



class identification_clusters:
	
	def __init__(self, spl,lspl):
		self.spl = spl
		self.lspl =lspl
		
		self.classified_peaklist= None
		self.calculated_peaks =None
		
	def clusters(self, error_rt, iso_length, idms_length, use_correlation, cor_threshold):
		self.classified_peaklist , self.calculated_peaks= clust.clusterization_CAMERA(self.spl,self.lspl,error_rt, \
					iso_length, use_correlation, cor_threshold,idms_length,)
		self.spl.set_mapped_peaks(self.classified_peaklist)
					
	def build_models(self, tree_model, peak_model,  cluster_model):
		#cluster_model
		for i, peak in enumerate(self.classified_peaklist._gen_peaks()):
			cluster_model.setItem(i, 0, QtGui.QStandardItem(peak.get_trans().toString()))
			cluster_model.setItem(i, 1, QtGui.QStandardItem(str(peak.get_rt())))
			cluster_model.setItem(i, 2, QtGui.QStandardItem(str(peak.get_area())))
			info_iso ="";info_frag=""
			for iso in peak.get_iso_cluster():
				info_iso += iso.get_trans().toString()+" "+ str(iso.get_rt())+'   '
			for add in peak.get_frag_cluster():
				info_frag += add.get_trans().toString()+" "+ str(add.get_rt())+'   '
			cluster_model.setItem(i, 3, QtGui.QStandardItem(info_iso))
			cluster_model.setItem(i, 4, QtGui.QStandardItem(info_frag))
		
		#peak_model
		
		for i, peak in enumerate(self.spl.get_peak_list()._gen_peaks()):
			peak_model.setItem(i, 0,QtGui.QStandardItem(peak.get_trans().toString()))
			peak_model.setItem(i, 1, QtGui.QStandardItem(str(peak.get_rt())))
			peak_model.setItem(i, 2, QtGui.QStandardItem(str(peak.get_area())))
			peak_model.setItem(i, 3, QtGui.QStandardItem(str(len(peak.get_iso_cluster()))))
			peak_model.setItem(i, 4, QtGui.QStandardItem(str(peak.get_iso_cluster().get_intra_corr())))
			peak_model.setItem(i, 5, QtGui.QStandardItem(str(len(peak.get_frag_cluster()))))
			peak_model.setItem(i, 6, QtGui.QStandardItem(str(peak.get_frag_cluster().get_intra_corr())))

		#tree view model
		xml = QtGui.QStandardItem(QtGui.QIcon(QtGui.QPixmap(path.normcase("gui/icons/grid.png"))), self.spl.getXmlFile())
		xml.setEditable(False)
		for peak in sorted(self.classified_peaklist, key = lambda chromatoPeak:chromatoPeak.get_trans_prec()):
			root  = QtGui.QStandardItem(QtGui.QIcon(QtGui.QPixmap(path.normcase("gui/icons/cluster.png"))), str(peak.get_trans_prec())+" "+str(peak.get_rt()))
			root.setEditable(False)
			isos = QtGui.QStandardItem("Isotopic_cluster")
			isos.setEditable(False)
			for iso in peak.get_iso_cluster():
				isos.appendRow(QtGui.QStandardItem(str(iso.get_trans_prec())+" "+str(iso.get_rt())))
			root.appendRow(isos)
			if peak.get_frag_cluster():
				frags = QtGui.QStandardItem("Fragments_adducts")
				frags.setEditable(False)
				for frag in peak.get_frag_cluster():
					frags.appendRow(QtGui.QStandardItem(str(frag.get_trans_prec())+" "+str(frag.get_rt())))
				root.appendRow(frags)
			xml.appendRow(root)
		tree_model.appendRow(xml)
		
		#return cluster_model, peak_model


	def print_res (self):
		with open(self.spl.getXmlFile()+"_clusters.txt", 'w') as f:
			for peak in self.classified_peaklist:
				f.write(str(peak.get_trans_prec())+";"+ str(peak.get_rt())+ ";"+ str(peak.get_area())+";")
				f.write(str(len(peak.get_frag_cluster()))+";")
				for add in peak.get_frag_cluster():
					f.write(str(add.get_trans_prec())+";"+ str(add.get_rt())+ ";"+ str(add.get_area())+";")
				for isotop in peak.get_iso_cluster():
					f.write(str(isotop.get_trans_prec())+";"+ str(isotop.get_rt())+ ";"+ str(isotop.get_area())+";")
				f.write("\n")
				
		with open(self.spl.getXmlFile()+".binary", 'w') as f:
			f.write("peak;rt;intensity;iso_length;is_isotopic_cluster;is_validation_iso;is_M0;frag_length;is_validation_adduct\n")
			for peak in self.spl.get_peak_list():
				f.write( str(peak.get_trans_prec())+";"+str(peak.get_rt())+";"+str(peak.get_area())+";"+str(len(peak.get_iso_cluster()))+";"+str(not peak.get_iso_cluster().is_empty())+";"+str(peak.get_iso_cluster().get_corr())+";"+str(not peak.get_frag_cluster().is_empty())+";"+str(len(peak.get_frag_cluster()))+";"+str(peak.get_frag_cluster().get_corr())+"\n")
			f.write("peak not found in the peaklist\n")
			for dic in self.calculated_peaks:
				for mass in dic.keys():
					f.write(str(mass)+";;;;;;"+str(len(dic[mass])==False)+";"+str(dic[mass][-1])+"\n")
					

if __name__ == "__main__":
	from PyQt4 import QtGui, QtCore
	from parsers import lxml_target
	import integration_peaks
	from core import clustering as clust, processing as proc, objects as obj
	import sys
	#from model import integration_peaks
	app = QtGui.QApplication(sys.argv)
	p1=lxml_target.lxml_parser("output-s6.mzXML")
	p1.parsing(3.03)
	p2=lxml_target.lxml_parser("output-s12.mzXML")
	p2.parsing(3.03)
	lspl=obj.ListSample()
	lspl.append(p1.getSpl())
	lspl.append(p2.getSpl())
	integr = integration_peaks.integration_by_xcms(lspl)
	integr.transformation()
	integr.integrate_align(max=10, snthresh =3)
	proc.creating_peakList(lspl)
	#peaks = proc.Merging_Peaks(lspl)
	#lspl[0].set_peak_list(peaks)
	id =identification_clusters( lspl[0],lspl)
	id.clusters()
	id.print_res()
	sys.exit(app.exec_())
